import uuid
from flaskapp.model.db import db, Alarm
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime
import logging

# Setup logging
logger = logging.getLogger(__name__)

def alarm_insert(box: dict, classType: str, conf: float, fp: str, target: str, mediaID: str) -> bool:
    try:
        current_datetime = datetime.now()
        alarm = Alarm(id=str(uuid.uuid4()), box=box, classType=classType, confidence=conf, file_path=fp, target=target, mediaID=mediaID, timestamp=current_datetime)
        db.session.add(alarm)
        db.session.commit()
        logger.info(f"Inserted alarm with id: {alarm.id}")
        return True
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error inserting alarm: {e}")
        return False

def alarm_delete(alarm_id: str) -> bool:
    try:
        alarm = Alarm.query.get(alarm_id)
        if alarm:
            db.session.delete(alarm)
            db.session.commit()
            logger.info(f"Deleted alarm with id: {alarm.id}")
            return True
        logger.warning(f"Alarm with id: {alarm_id} not found")
        return False
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error deleting alarm: {e}")
        return False

def alarm_get(page: int = 1, per_page: int = 10, classType: str = None) -> dict:
    try:
        logger.info(f"Fetching alarms for page: {page}, per_page: {per_page}, classType: {classType}")
        query = Alarm.query.order_by(Alarm.timestamp.desc())
        if classType and classType.upper() == "ALL":
            # 如果 classType 是 "all" 或者 "ALL"，则不添加过滤条件，返回所有记录
            pass
        elif classType:
            # 否则，根据指定的 classType 进行过滤
            query = query.filter(Alarm.classType == classType)
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        alarms = [alarm.to_dict() for alarm in pagination.items]
        logger.info(f"Retrieved {len(alarms)} alarms from page {page}, total items: {pagination.total}, total pages: {pagination.pages}")
        return {
            "alarms": alarms,
            "total": pagination.total
        }
    except SQLAlchemyError as e:
        logger.error(f"Error retrieving alarms: {e}")
        return {"alarms": [], "total_pages": 0, "current_page": 0, "total_items": 0}



